package tech.horgee.dao;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.util.SaFoxUtil;
import tech.horgee.utils.RedisUtil;

import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * satoken持久化
 */
public class SaTokenCacheDao implements SaTokenDao {
    @Override
    public String get(String key) {
        return RedisUtil.getCacheObject(key);
    }

    @Override
    public void set(String key, String value, long timeout) {
        if (timeout != 0L && timeout > -2L) {
            if (timeout == -1) {
                RedisUtil.setCacheObject(key, value);
            } else {
                RedisUtil.setCacheObject(key, value, timeout, ChronoUnit.SECONDS);
            }
        }
    }

    @Override
    public void update(String key, String value) {
        long expire = this.getTimeout(key);
        if (expire != -2L) {
            this.set(key, value, expire);
        }
    }

    @Override
    public void delete(String key) {
        RedisUtil.deleteObject(key);
    }

    @Override
    public long getTimeout(String key) {
        return RedisUtil.getTimeToLive(key);
    }

    @Override
    public void updateTimeout(String key, long timeout) {
        if (timeout == -1L) {
            long expire = this.getTimeout(key);
            if (expire != -1L) {
                this.set(key, this.get(key), timeout);
            }
        } else {
            RedisUtil.expire(key, timeout, ChronoUnit.SECONDS);
        }
    }

    @Override
    public Object getObject(String key) {
        return RedisUtil.getCacheObject(key);
    }

    @Override
    public void setObject(String key, Object object, long timeout) {
        if (timeout != 0L && timeout > -2L) {
            if (timeout == -1) {
                RedisUtil.setCacheObject(key, object);
            } else {
                RedisUtil.setCacheObject(key, object, timeout, ChronoUnit.SECONDS);
            }
        }
    }

    @Override
    public void updateObject(String key, Object object) {
        long expire = this.getObjectTimeout(key);
        if (expire != -2L) {
            this.setObject(key, object, expire);
        }
    }

    @Override
    public void deleteObject(String key) {
        RedisUtil.deleteObject(key);
    }

    @Override
    public long getObjectTimeout(String key) {
        return RedisUtil.getTimeToLive(key);
    }

    @Override
    public void updateObjectTimeout(String key, long timeout) {
        if (timeout == -1L) {
            long expire = this.getTimeout(key);
            if (expire != -1L) {
                this.set(key, this.get(key), timeout);
            }
        } else {
            RedisUtil.expire(key, timeout, ChronoUnit.SECONDS);
        }
    }

    @Override
    public List<String> searchData(String prefix, String keyword, int start, int size, boolean sortType) {
        List<String> list = RedisUtil.keys(prefix + "*" + keyword + "*");
        return SaFoxUtil.searchList(list, start, size, sortType);
    }

}
